package study2018._0115;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;

import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.Field.Index;
import org.apache.lucene.document.Field.Store;
import org.apache.lucene.index.CorruptIndexException;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.index.IndexWriterConfig.OpenMode;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.store.LockObtainFailedException;
import org.apache.lucene.util.Version;

public class LunceneWriter {
	private static String INDEX_PATH = "D:\\study\\luncene\\index";
	private static String SOURCE_PATH = "D:\\study\\luncene\\source";

	public static void main(String[] args) throws CorruptIndexException, LockObtainFailedException, IOException {
		Directory directory = FSDirectory.open(new File(INDEX_PATH));
		IndexWriterConfig indexWriterConfig = new IndexWriterConfig(Version.LUCENE_35, new StandardAnalyzer(Version.LUCENE_35));
		indexWriterConfig.setOpenMode(OpenMode.CREATE);
		IndexWriter indexWriter = new IndexWriter(directory, indexWriterConfig);

		File[] files = new File(SOURCE_PATH).listFiles();
		for (File f : files) {
			Document doc = new Document();
			String content = FileReaderAll(f.getCanonicalPath(), "GBK");
			Field field = new Field("content", content, Store.YES, Index.ANALYZED);
			doc.add(field);
			indexWriter.addDocument(doc);
		}
		indexWriter.close();
	}

	public static String FileReaderAll(String FileName, String charset) throws IOException {
		BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(FileName), charset));
		String line = new String();
		String temp = new String();

		while ((line = reader.readLine()) != null) {
			temp += line;
		}
		reader.close();
		return temp;
	}
}
